package com.glsc.ngateway.wordconver.controller;

import com.glsc.ngateway.wordconver.service.WordToPdfService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Objects;

/**
 * @author xuchang
 */
@RestController
@RequestMapping("/word")
public class WordController {

    @Resource
    private WordToPdfService wordToPdfService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/word2Pdf")
    public String word2Pdf(@RequestParam String wordPath) {
        logger.info("WordController.word2Pdf文件路徑：" + wordPath);
        try {
            return wordToPdfService.toPdf(wordPath);
        } catch (Exception e) {
            return "";
        }
    }


    @RequestMapping(method = RequestMethod.POST, value = "/uploadWord2Pdf", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public byte[] uploadWord2Pdf(@RequestPart(value = "file") MultipartFile file) {
        logger.info("WordController.uploadWord2Pdf请求文件：" + file.getOriginalFilename());
        return wordToPdfService.converToPdf(file);
    }


    @RequestMapping(method = RequestMethod.POST, value = "/getPdfFromOaUrl")
    public ResponseEntity<byte[]> getPdfFromOaUrl(@RequestParam(value = "srcPath") String srcPath, @RequestParam(value = "sessionId") String sessionId) throws IOException {
        logger.info(String.format("页面截图转pdf:srcPath, %s,sessionId, %s", srcPath, sessionId));
        byte[] bytes = wordToPdfService.getPdfFromOaUrl(srcPath, sessionId);
        return Objects.nonNull(bytes) && bytes.length > 0 ? ResponseEntity.ok(bytes) : ResponseEntity.badRequest().build();
    }

//    @RequestMapping(method = RequestMethod.POST, value = "/signPdf")
    public ResponseEntity<byte[]> signPdf(@RequestPart(value = "pdf") MultipartFile pdf, @RequestPart(value = "gif") MultipartFile gif, @RequestParam(value = "account") String account) throws IOException {
        logger.info("WordController.signPdf：pdf-{}, gif-{}", pdf.getOriginalFilename(), gif.getOriginalFilename());
        byte[] bytes = wordToPdfService.signPdfWithAccount(pdf, gif, account);
        return Objects.nonNull(bytes) && bytes.length > 0 ? ResponseEntity.ok(bytes) : ResponseEntity.badRequest().build();
    }

}
